package com.itqf.realm;

import com.itqf.entity.SysUsers;
import com.itqf.service.SysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2021/2/1
 * @Time: 上午10:07
 */
public class MyUsersRealm  extends AuthorizingRealm {


    @Autowired//spring容器中注入
    private SysUserService sysUserService;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    //  SimpleAuthenticationInfo info = new SimpleAuthenticationInfo
        //                (sysUsers,sysUsers.getPwd(),ByteSource.Util.bytes(sysUsers.getSalt()),this.getName());
      SysUsers  sysUsers =  (SysUsers) principals.getPrimaryPrincipal();
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("---->认证");
        String loginname = (String)token.getPrincipal();
       // String pwd = new String((char[])token.getCredentials());
        SysUsers sysUsers = sysUserService.findByLoginname(loginname);

        if (sysUsers==null){
            throw new UnknownAccountException("未知的账户");
        }
//        if (!pwd.equals(sysUsers.getPwd())){
//            throw  new IncorrectCredentialsException("密码错误");
//        }

//        SimpleAuthenticationInfo info =
//                new SimpleAuthenticationInfo(sysUsers,pwd,this.getName());

        //shiro比较密码 把传过来的密码加盐+迭代加密后+数据库的密文比较
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo
                (sysUsers,sysUsers.getPwd(),ByteSource.Util.bytes(sysUsers.getSalt()),this.getName());

        return info;
    }
}
